#include "packs.h"
#include "thirdparty/tinyxml/tinyxml.h"
#include <QFile>

namespace yc {

Packs::Packs(const QString& file_name)
{
    QFile file(file_name);
    if (file.open(QFile::ReadOnly)) {
        QByteArray ba = file.readAll();
        file.close();

        TiXmlDocument doc;
        doc.Parse(ba.data());
        if (const TiXmlElement* root = doc.RootElement()) {
            const TiXmlElement* e = root->FirstChildElement("pack");
            while (e) {
                if (const char* attr = e->Attribute("version")) {
                    Pack p;
                    p.version = attr;
                    attr = e->Attribute("next");
                    if (attr) {
                        p.next = attr;
                    }
                    attr = e->Attribute("url");
                    if (attr) {
                        p.url = attr;
                    }
                    attr = e->Attribute("md5");
                    if (attr) {
                        p.md5 = attr;
                    }
                    attr = e->Attribute("date");
                    if (attr) {
                        p.date = attr;
                    }
                    attr = e->Attribute("mode");
                    if (attr) {
                        p.mode = QString(attr).toInt();
                    }
                    attr = e->Attribute("size");
                    if (attr) {
                        p.size = QString(attr).toInt();
                    }
                    attr = e->Attribute("appVersion");
                    if (attr) {
                        p.app_version = QString(attr);
                    }
                    attr = e->GetText();
                    if (attr) {
                        p.comment = QString::fromUtf8(attr);
                    }
                    packs_.insert(p.version, p);
                }
                e = e->NextSiblingElement("pack");
            }
        }
    }
}

QList<Pack> Packs::nextPacks(const QString& version) const
{
    QList<Pack> packs;
    QHash<QString, Pack>::const_iterator end = packs_.constEnd();
    QHash<QString, Pack>::const_iterator it = packs_.constFind(version);
    if (it != end && !it.value().next.isEmpty()) {
        it = packs_.constFind(it.value().next);
        if (it != end) {
            while (it != end) {
                packs.append(it.value());
                if (it.value().next.isEmpty()) {
                    break;
                } else {
                    it = packs_.constFind(it.value().next);
                }
            }
        }
    }
    return packs;
}

} // namespace yc
